package net.hserver.socket.client;


import net.hserver.socket.common.Handler;
import net.hserver.socket.common.HSocketContext;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.StandardSocketOptions;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;

public class HSocketClient {

    private String ip;
    private Integer port;
    private Handler handler;

    public HSocketClient(String ip, Integer port) {
        this.ip = ip;
        this.port = port;
    }

    public HSocketClient addHandler(Handler handler) {
        this.handler = handler;
        return this;
    }

    public void start() {
        // 开启通道
        try {
            AsynchronousSocketChannel channel = AsynchronousSocketChannel.open();
            channel.setOption(StandardSocketOptions.TCP_NODELAY, true);
            channel.setOption(StandardSocketOptions.SO_SNDBUF, 1024);
            channel.setOption(StandardSocketOptions.SO_RCVBUF, 1024);
            //建立连接
            channel.connect(new InetSocketAddress(ip, port), null, new CompletionHandler<Void, Object>() {

                @Override
                public void completed(Void result, Object attachment) {
                    //初始化
                    new HSocketContext(channel, handler);
                }

                @Override
                public void failed(Throwable exc, Object attachment) {

                }
            });

        } catch (IOException e) {
            e.printStackTrace();
        }
    }


}
